package config

import "fmt"

// MongoDBConfig 结构体对应 YAML 配置
type Mongo struct {
	Host              string `yaml:"host"`
	Port              int    `yaml:"port"`
	Database          string `yaml:"database"`
	Username          string `yaml:"username"`
	Password          string `yaml:"password"`
	AuthSource        string `yaml:"auth_source"`
	ReplicaSet        string `yaml:"replica_set"`
	SSL               bool   `yaml:"ssl"`
	ConnectionOptions struct {
		MaxPoolSize      int    `yaml:"max_pool_size"`
		MinPoolSize      int    `yaml:"min_pool_size"`
		ConnectTimeoutMs int    `yaml:"connect_timeout_ms"`
		SocketTimeoutMs  int    `yaml:"socket_timeout_ms"`
		ReadPreference   string `yaml:"read_preference"`
		WriteConcern     string `yaml:"write_concern"`
	} `yaml:"connection_options"`
}

func (m Mongo) Dsn() string {
	// 默认值处理
	host := m.Host
	if host == "" {
		host = "localhost"
	}

	port := m.Port
	if port == 0 {
		port = 27017
	}

	// 处理是否需要用户名密码
	if m.Username != "" && m.Password != "" {
		return fmt.Sprintf("mongodb://%s:%s@%s:%d/%s?authSource=%s",
			m.Username, m.Password, host, port, m.Database, m.AuthSource)
	} else {
		return fmt.Sprintf("mongodb://%s:%d/%s", host, port, m.Database)
	}
}
